﻿using System;
using System.Web;
using System.IO;
using ncp.Business.Common;

namespace ncp.Web.handler
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    //[WebService(Namespace = "http://tempuri.org/")]
    //[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var userInfo = context.Request["uname"];
            HttpPostedFile file = context.Request.Files["Filedata"];

            string uploadPath =HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\";
            
            if (userInfo != "")
            {
                uploadPath = uploadPath + userInfo + "\\";
                if (file != null)
                {
                    //格式验证
                    string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };          //文件允许格式
                    string[] temp = file.FileName.Split('.');
                     string currentType = "." + temp[temp.Length - 1].ToLower();
                    if (Array.IndexOf(filetype, currentType) != -1)
                    {
                        //重命名
                        string fileName = Guid.NewGuid().ToString().Replace("-", "") + currentType;

                        if (!Directory.Exists(uploadPath))
                        {
                            Directory.CreateDirectory(uploadPath);
                        }
                        file.SaveAs(uploadPath + fileName);
                        //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                        context.Response.Write("/uploadFiles/"+userInfo+"/" + fileName);
                    }
                    else
                    {
                        context.Response.Write("0");
                    }
                }
                else
                {
                    context.Response.Write("0");
                }
            }
            else
            {
                context.Response.Write("0");
            } 
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
